package com.wpzf.ndhc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wpzf.common.core.utils.StringUtils;
import com.wpzf.common.core.utils.sign.Base64;
import com.wpzf.ndhc.utils.TableUtil;
import com.wpzf.ndhc.domain.*;
import com.wpzf.ndhc.mapper.WpzfNdhcAppMapper;
import com.wpzf.ndhc.mapper.WpzfNdhcSqthMapper;
import com.wpzf.ndhc.mapper.WpzfNdhcXjtbTbBaseMapper;
import com.wpzf.ndhc.service.WpzfNdhcSqthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WpzfNdhcSqthServiceImpl implements WpzfNdhcSqthService {

    @Autowired
    private WpzfNdhcSqthMapper wpzfNdhcSqthMapper;

    @Autowired
    private WpzfNdhcXjtbTbBaseMapper wpzfNdhcXjtbTbBaseMapper;

    @Autowired
    private WpzfNdhcAppMapper wpzfNdhcAppMapper;

    @Override
    public List<Map<String, Object>> getPch(Map<String, Object> param) {
        param = TableUtil.TableName(param);
        return wpzfNdhcSqthMapper.getPch(param);
    }

    @Override
    public List<Map<String, Object>> getDkList(Map<String, Object> param) {
        param = TableUtil.TableName(param);
        return wpzfNdhcSqthMapper.getDkList(param);
    }

    @Override
    public Integer getDkListCount(Map<String, Object> param) {
        param = TableUtil.TableName(param);
        return wpzfNdhcSqthMapper.getDkListCount(param);
    }

    @Override
    public WpCjTbxxbxjNdDTO querytbxxByjcbh(Map<String, Object> param) {
        param = TableUtil.TableName(param);
        return wpzfNdhcSqthMapper.querytbxxByjcbh(param);
    }

    @Override
    public WpCjTbxxbxjNdDTO querytbxxNdByjcbh(Map<String, Object> param) {
        param = TableUtil.TableName(param);
        return wpzfNdhcSqthMapper.querytbxxNdByjcbh(param);
    }

    @Override
    public WpCjGsinfolyNdDTO getGsinfoly(Map<String, Object> param) {
        param = TableUtil.TableName(param);
        return wpzfNdhcXjtbTbBaseMapper.getGsinfoly(param);
    }

    @Override
    public String getInfo(Map<String, Object> parm) {
        parm = TableUtil.TableName(parm);

        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> dataList = new ArrayList<>();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> main = new HashMap<>();
        Map<String, Object> wpzfdk = new HashMap<>();
        Map<String, Object> tbxxbxj = wpzfNdhcAppMapper.queryTbxxbxj(parm);
        wpzfdk.put("tbbsm", "");
        wpzfdk.put("tbbh", "");
        wpzfdk.put("dkbh", "");
        wpzfdk.put("sjtbmj", "");
        wpzfdk.put("jcrq", "");
        wpzfdk.put("xzqdm", "");
        wpzfdk.put("tbfl", "");
        wpzfdk.put("xzmc", "");
        wpzfdk.put("csmc", "");
        wpzfdk.put("xxdz", "");
        wpzfdk.put("geometry", tbxxbxj.get("wkt"));
        wpzfdk.put("dlrdnydmj", "");
        wpzfdk.put("dlrdgdmj", "");
        wpzfdk.put("yjjbntmj", "");
        wpzfdk.put("wsx_dlrdstmj", "");
        wpzfdk.put("stbhhxmj", "");
        wpzfdk.put("hcjl", "");
        wpzfdk.put("tblx", "");
        wpzfdk.put("sjyt", "");
        wpzfdk.put("sjyt2", "");
        wpzfdk.put("hfsjyt", "");
        wpzfdk.put("hfpdyjsm", "");
        wpzfdk.put("nydmj", "");
        wpzfdk.put("gdmj", "");
        wpzfdk.put("stmj", "");
        wpzfdk.put("sjdkmj", "");
        wpzfdk.put("tb_stbhhxmj", "");
        wpzfdk.put("wflx1", "");
        wpzfdk.put("wflx2", "");
        wpzfdk.put("wflx3", "");
        wpzfdk.put("wflx4", "");
        wpzfdk.put("lzgdjf", "");
        wpzfdk.put("sywhzj", "");
        wpzfdk.put("sfdpf", "");
        wpzfdk.put("wfsjyt", "");
        wpzfdk.put("wfpdyjsm", "");
        wpzfdk.put("sfjsyd", "");
        wpzfdk.put("tbjsqk", "");
        wpzfdk.put("wf_xmmc", "");
        wpzfdk.put("wf_xmzt", "");
        wpzfdk.put("wf_xmlx", "");
        wpzfdk.put("wf_lxpzjg", "");
        wpzfdk.put("wf_lxpzwh", "");
        wpzfdk.put("wf_clfs", "");
        wpzfdk.put("sfylwsss", "");
        wpzfdk.put("sfbzxajzf", "");
        wpzfdk.put("sfjjxm", "");
        wpzfdk.put("wf_labh", "");
        wpzfdk.put("yjbm", "");
        wpzfdk.put("zglsdwqk", "");
        wpzfdk.put("fgymmj", "");
        wpzfdk.put("fgdwmj", "");
        wpzfdk.put("ccfg_yjjbnt", "");
        wpzfdk.put("ccfg_stbhq", "");
        wpzfdk.put("fgysdw", "");
        wpzfdk.put("fgysfzr", "");
        wpzfdk.put("qtydsjyt", "");
        wpzfdk.put("qtydsjyt2", "");
        wpzfdk.put("pwsj", "");
        wpzfdk.put("qtpdyjsm", "");

        Map<String, Object> other = new HashMap<>();
        List<Map<String, Object>> hcfjList = new ArrayList<>();
        List<Map<String, Object>> reTaskdetailAnnexList = wpzfNdhcAppMapper.queryReTaskdetailAnnex(parm);
        for (Map<String, Object> reTaskdetailAnnex : reTaskdetailAnnexList) {
            String fj = reTaskdetailAnnex.get("fj") + "";
            if (fj.indexOf("jpg") != -1) {
                //todo
                Map<String, Object> hcfj = new HashMap<>();
                hcfj.put("bsm", "");
                hcfj.put("xzqdm", "");
                hcfj.put("tbbsm", "");
                hcfj.put("tbbh", "");
                hcfj.put("fjmc", reTaskdetailAnnex.get("fjmc"));
                hcfj.put("lysb", "");
//                hcfj.put("fjlx", "IMAGE");
                hcfj.put("fjlx", reTaskdetailAnnex.get("fjlx"));
                hcfj.put("psry", reTaskdetailAnnex.get("psry"));
                hcfj.put("pssj", reTaskdetailAnnex.get("pssj"));
                hcfj.put("longitude", reTaskdetailAnnex.get("longitude"));
                hcfj.put("latitude", reTaskdetailAnnex.get("latitude"));
                hcfj.put("psjd", reTaskdetailAnnex.get("psjd"));
                hcfj.put("psgd", reTaskdetailAnnex.get("psgd"));
                hcfj.put("psfyj", reTaskdetailAnnex.get("psfyj"));
                hcfj.put("psaltitude", reTaskdetailAnnex.get("psaltitude"));
                hcfj.put("takeofflon", "");
                hcfj.put("takeofflat", "");
                hcfj.put("takeoffrelheight", "");
                hcfj.put("takeoffaltitude", "");
                hcfj.put("metarecord", "");
                hcfj.put("arg", "");
                hcfj.put("url", reTaskdetailAnnex.get("fj"));

                hcfj.put("creator", reTaskdetailAnnex.get("creator"));
                hcfj.put("xzb", reTaskdetailAnnex.get("xzb"));
                hcfj.put("yzb", reTaskdetailAnnex.get("yzb"));
                hcfj.put("ower_lever", reTaskdetailAnnex.get("ower_lever"));
                hcfj.put("uuid", reTaskdetailAnnex.get("uuid"));
                hcfj.put("dkbh", reTaskdetailAnnex.get("dkbh"));

                hcfjList.add(hcfj);
            }
        }


        other.put("pwinfo", new ArrayList<>());
        other.put("fjinfo", new ArrayList<>());
        other.put("hcfj", hcfjList);
        data.put("other", other);
        main.put("wpzfdk", wpzfdk);
        data.put("main", main);
        dataList.add(data);
        map.put("data", dataList);
        JSONObject jsonObject = new JSONObject(map);
        System.out.println(jsonObject.toJSONString());
        return jsonObject.toJSONString();
    }

    @Override
    public ModelMap getShowImgsnew(Map<String, Object> parm) {
        parm = TableUtil.TableName(parm);
        ModelMap map = new ModelMap();
        try {
            String tbbhs = parm.get("tbbh") + "";
            String xzqdm = parm.get("xzqdm") + "";
            String pch = parm.get("pch") + "";
            String postURL = "";
            String data = "";
            String strXzqdm = parm.get("xzqdm").toString().substring(0, 2);
            {
                postURL = "https://jg.landcloud.org.cn:8553/webapi/token";
                data = "client_id=web&client_secret=e46232c20609435eba54b7576de935dd&grant_type=password&username=a53e0c14ee900728f36bba014d975982&password=b30c775c48e9ba92ade95e427a5242b0";
            }
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");

            out.write(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();

            byteArrayOutputStream.close();
            //关闭流
            is.close();

            conn.disconnect();
            String result = new String(datas, 0, datas.length, "utf-8");
            List<String> items = new ArrayList<>();
            {
                String t = getImgnew(result, "00gty_wpzf_nddk", xzqdm, tbbhs);
                items.add(t);
                map.put("data", items);
            }
        } catch (MalformedURLException ex) {
            throw new RuntimeException(ex);
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        return map;
    }

    public String getImgnew(String str, String ywmb, String xzqdm, String tbbh) {
        String rest = "";
        try {
            String postURL = "";
            String token = "";
            String token_type = "";
            Map mapType = JSON.parseObject(str, Map.class);
            {
                for (Object obj : mapType.keySet()) {

                    if ((obj + "").equals("access_token")) {
                        token = mapType.get("access_token") + "";
                        token_type = mapType.get("token_type") + "";
                    }
                }
                System.out.println(token);
                //接口地址
                postURL = "https://dc2.landcloud.org.cn:9443/webapi/api/open/GetWPZFTBInfo";
            }
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            String encoding = Base64.encode(str.getBytes());
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8 ");
            conn.setRequestProperty("Authorization", token_type + " " + token);
            //  conn.setRequestProperty("token", token);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(2000);
            conn.setReadTimeout(2000);
            //获取URLConnection对象对应的输出流
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            //  out = new PrintWriter(conn.getOutputStream());
            //发送请求参数即数据
            //String xmbh="210115S120240216LJ00005";
            if (StringUtils.isNotBlank(xzqdm)) {
                //String data = "{\"xzqdm\":\"" + xzqdm + "\",\"ywmb\":\"" + ywmb + "\"}";
                String data = "{\"xzqdm\":\"" + xzqdm + "\",\"ywmb\":\"" + ywmb + "\",\"xmbh\":[\"" + tbbh + "\"]}";
                System.out.println("---------获取地块列表参数------" + data);
                out.write(data);
                out.flush();
                InputStream is = conn.getInputStream();
                int count = 0;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                while ((count = is.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, count);
                }
                byte[] datas = byteArrayOutputStream.toByteArray();

                byteArrayOutputStream.close();
                is.close();
                conn.disconnect();
                rest = new String(datas, 0, datas.length, "utf-8");
            }

        } catch (Exception e) {
            rest = "网络异常，请稍后重试！";
            //writeLog(UtilTool.GetTime_1()+"："+e.getMessage()+"\n");
            throw new RuntimeException(e.getMessage());
        }
        return rest;
    }

    @Override
    public ModelMap getShowImgs(Map<String, Object> parm) {
        ModelMap map = new ModelMap();
        try {
            String tbbhs = parm.get("tbbh") + "";
            String xzqdm = parm.get("xzqdm") + "";
            String pch = parm.get("pch") + "";
            String postURL = "";
            String data = "";
            String strXzqdm = parm.get("xzqdm").toString().substring(0, 2);
            {
                postURL = "https://jg.landcloud.org.cn:8553/webapi/token";
                data = "client_id=web&client_secret=e46232c20609435eba54b7576de935dd&grant_type=password&username=a53e0c14ee900728f36bba014d975982&password=b30c775c48e9ba92ade95e427a5242b0";
            }
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");

            out.write(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();

            byteArrayOutputStream.close();
            //关闭流
            is.close();

            conn.disconnect();
            String result = new String(datas, 0, datas.length, "utf-8");
            List<String> items = new ArrayList<>();
            {
                String t = getImg(result, "00gty_wpzf_nddk", xzqdm, tbbhs);
                items.add(t);
                map.put("data", items);
            }
        } catch (MalformedURLException ex) {
            throw new RuntimeException(ex);
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        return map;
    }

    public String getImg(String str, String ywmb, String xzqdm, String tbbh) {
        String rest = "";
        try {
            String postURL = "";
            String token = "";
            String token_type = "";
            Map mapType = JSON.parseObject(str, Map.class);
            {
                for (Object obj : mapType.keySet()) {

                    if ((obj + "").equals("access_token")) {
                        token = mapType.get("access_token") + "";
                        token_type = mapType.get("token_type") + "";
                    }
                }
                System.out.println(token);
                //接口地址
                postURL = "https://dc2.landcloud.org.cn:9443/webapi/api/open/GetWPZFTBInfo";
            }
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            String encoding = Base64.encode(str.getBytes());
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8 ");
            conn.setRequestProperty("Authorization", token_type + " " + token);
            //  conn.setRequestProperty("token", token);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(2000);
            conn.setReadTimeout(2000);
            //获取URLConnection对象对应的输出流
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            //  out = new PrintWriter(conn.getOutputStream());
            //发送请求参数即数据
            //String xmbh="210115S120240216LJ00005";
            if (StringUtils.isNotBlank(xzqdm)) {
                //String data = "{\"xzqdm\":\"" + xzqdm + "\",\"ywmb\":\"" + ywmb + "\"}";
                String data = "{\"xzqdm\":\"" + xzqdm + "\",\"ywmb\":\"" + ywmb + "\",\"xmbh\":[\"" + tbbh + "\"]}";
                System.out.println("---------获取地块列表参数------" + data);
                out.write(data);
                out.flush();
                InputStream is = conn.getInputStream();
                int count = 0;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                while ((count = is.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, count);
                }
                byte[] datas = byteArrayOutputStream.toByteArray();

                byteArrayOutputStream.close();
                is.close();
                conn.disconnect();
                rest = new String(datas, 0, datas.length, "utf-8");
            }

        } catch (Exception e) {
            rest = "网络异常，请稍后重试！";
            //writeLog(UtilTool.GetTime_1()+"："+e.getMessage()+"\n");
            throw new RuntimeException(e.getMessage());
        }
        return rest;
    }

    @Override
    public List<WpCjDkxxbxjNdDTO> querydkxxBytbbh(Map<String, Object> parm) {
        parm = TableUtil.TableName(parm);
        return wpzfNdhcSqthMapper.querydkxxBytbbh(parm);
    }


    @Override
    public List<WpCjTbjtNdDTO> querytbjtBytbbh(Map<String, Object> parm) {
        String tbbh = parm.get("tbbh").toString();
        String xzqdm = parm.get("xzqdm").toString();
        String pch = parm.get("pch").toString();
        String url = "";

        String xzq = parm.get("xzqdm").toString().substring(0, 2);
//        String dkbh = MyStringUtils.truncateString(tbbh);
        String jcbh = "";
        if (tbbh.indexOf(",") != -1) {
            String s = tbbh.split(",")[0];
            if (s.indexOf("-") != -1) {
                jcbh = s.substring(0, s.indexOf("-"));
            } else {
                jcbh = tbbh;
            }
        } else {
            if (tbbh.indexOf("-") != -1) {
                jcbh = tbbh.substring(0, tbbh.indexOf("-"));
            } else {
                jcbh = tbbh;
            }
        }

        List<WpCjTbjtNdDTO> lists = new ArrayList<>();
        WpCjTbjtNdDTO model = new WpCjTbjtNdDTO();
        model.setName("用地管理信息套合示意图");
        url = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/upload/photo/wpzf2024/" + pch + "/" + xzq + "/" + xzqdm + "/" + jcbh + "_YDGL.jpg";
        model.setUrl(url);
        lists.add(model);

        model = new WpCjTbjtNdDTO();
        model.setName("耕地套合示意图");
        url = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/upload/photo/wpzf2024/" + pch + "/" + xzq + "/" + xzqdm + "/" + jcbh + "_GD.jpg";
        model.setUrl(url);
        lists.add(model);

        model = new WpCjTbjtNdDTO();
        model.setName("设施农用地备案示意图");
        url = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/upload/photo/wpzf2024/" + pch + "/" + xzq + "/" + xzqdm + "/" + jcbh + "_SSNYD.jpg";

        model.setUrl(url);
        lists.add(model);

        return lists;
    }

    @Override
    public WpCjTbhcjgshijNdDTO queryTbhcjgshijBytbbh(Map<String, Object> param) {
        param = TableUtil.TableName(param);
        return wpzfNdhcSqthMapper.queryTbhcjgshijBytbbh(param);
    }

    @Override
    public WpCjTbhcjgsjNdDTO queryTbhcjgsjBytbbh(Map<String, Object> param) {
        param = TableUtil.TableName(param);
        return wpzfNdhcSqthMapper.queryTbhcjgsjBytbbh(param);
    }

    @Override
    public WpCjGjjThDkNdDTO queryGjjThDkByTbbh(Map<String, Object> param) {
        param = TableUtil.TableName(param);
        return wpzfNdhcSqthMapper.queryGjjThDkByTbbh(param);
    }

    @Override
    @Transactional
    public Integer thDk(Map<String, Object> param) {
        param = TableUtil.TableName(param);
        wpzfNdhcSqthMapper.updateThDkStatusByDkbh(param);
        param.put("sqsj", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
        return wpzfNdhcSqthMapper.saveThDk(param);
    }

    @Override
    public List<WpCjGjjThDkNdDTO> queryGjjThDkList(Map<String, Object> param) {
        param = TableUtil.TableName(param);
        return wpzfNdhcSqthMapper.queryGjjThDkList(param);
    }


}
